<template>
  <view class="page page-primary">
    <page-header theme="colorful"></page-header>
    <view class="page-content">
      <!-- 头部卡片 -->
      <view class="page-card-div">
        <view class="card-title row-flex">
          <image
            class="img-icon"
            :src="`/static/images/icon-${isPersonal ? 'gr' : 'gs'}.png`"
            mode=""
          ></image>
          <view>{{ companyData.title }}</view>
        </view>
        <view class="card-tags row-flex">
          <fui-tag
            :text="companyData.type"
            type="danger"
            :background="tagsColor.tagBack"
            :color="tagsColor.tagColor"
          ></fui-tag>
          <fui-tag
            v-if="companyData.type === '已启用' && !isPersonal"
            text="公司认证"
            v-show="companyData.isCompanyAuth"
            type="danger"
            background="#fff4e5"
            color="#FCAD4C"
          ></fui-tag>
        </view>
        <view class="card-row row-flex" v-if="!isPersonal">
          <view class="card-row-left">社会信用代码</view>
          <view class="card-row-right">{{ companyData.code }}</view>
        </view>
        <view class="card-row row-flex">
          <view class="card-row-left">登录手机号</view>
          <view class="card-row-right">
            <template v-if="isEyesOpen">
              {{ maskPhoneNumber(companyData.headPhone) }}
              <span class="icon iconfont icon-close-eyes" @click="eyesClick(1)"
                >&#xe901;</span
              >
            </template>
            <template v-else>
              {{ companyData.headPhone }}
              <span class="icon iconfont icon-close-eyes" @click="eyesClick(2)"
                >&#xe60f;</span
              >
            </template>
          </view>
        </view>
        <template v-if="!isPersonal && companyData.type != '邀约中'">
          <view class="card-row row-flex">
            <view class="card-row-left">公司地址</view>
            <view class="card-row-right">{{ companyData.address }}</view>
          </view>
        </template>
        <view class="card-row row-flex">
          <view class="card-row-left">法人姓名</view>
          <view class="card-row-right">{{ companyData.headName }}</view>
        </view>
        <template v-if="!isPersonal && companyData.type != '邀约中'">
          <!-- <view class="card-row row-flex">
            <view class="card-row-left">公司描述</view>
            <view class="card-row-right">{{ companyData.description }}</view>
          </view> -->
          <view class="card-row row-flex">
            <view class="card-row-left">营业执照</view>
            <view
              class="card-row-right text-blue"
              @click="checkID('img', companyData.businessLicense)"
              >查看营业执照
            </view>
          </view>
        </template>
      </view>
      <!-- 法人信息 -->
      <template v-if="false">
        <view class="page-title">法人信息</view>
        <view class="page-card-div card-mag">
          <view class="card-row row-flex">
            <view class="card-row-left">姓名</view>
            <view class="card-row-right">{{ companyData.corporateName }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">联系方式</view>
            <view class="card-row-right"
              >{{ maskPhoneNumber(companyData.corporatePhone) }}
            </view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">身份证号</view>
            <view class="card-row-right">{{
              maskIdCardNumber(companyData.corporateID)
            }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">法人证件</view>
            <view
              class="card-row-right text-blue"
              @click="checkID('ID', companyData.idcBack, companyData.idcFront)"
              >查看法人证件</view
            >
          </view>
        </view>
      </template>
      <!-- 负责人信息 -->
      <view class="page-title">负责人信息</view>
      <view class="page-card-div card-mag">
        <view class="card-row row-flex">
          <view class="card-row-left">姓名</view>
          <view class="card-row-right">{{ companyData.headName }}</view>
        </view>
        <view class="card-row row-flex">
          <view class="card-row-left">联系方式</view>
          <view class="card-row-right"
            >{{ maskPhoneNumber(companyData.headPhone) }}
          </view>
        </view>
        <view class="card-row row-flex" v-if="companyData.type != '邀约中'">
          <view class="card-row-left">身份证号</view>
          <view class="card-row-right">{{
            maskIdCardNumber(companyData.headID)
          }}</view>
        </view>
        <view class="card-row row-flex" v-if="companyData.type != '邀约中'">
          <view class="card-row-left">负责人证件</view>
          <view
            class="card-row-right text-blue"
            @click="checkID('ID', companyData.adminCardFront, companyData.adminCardBack)"
            >查看负责人证件</view
          >
        </view>
      </view>
      <!-- 银行信息 -->
      <!-- <template v-if="companyData.type != '邀约中'">
        <view class="page-title">银行信息</view>
        <view class="page-card-div card-mag">
          <view class="card-row row-flex">
            <view class="card-row-left">银行开户名</view>
            <view class="card-row-right">{{ companyData.bankNname }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">开户行支行</view>
            <view class="card-row-right">{{ companyData.openBank }} </view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">银行账号</view>
            <view class="card-row-right">{{ companyData.bankID }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">备案ID</view>
            <view class="card-row-right">{{ companyData.filingsID }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">认证时间</view>
            <view class="card-row-right">{{
              utils.dateFormatter(companyData.checkTime, "y-m-d h:i:s", 2, true)
            }}</view>
          </view>
        </view>
      </template> -->
      <!-- 驳回信息 -->
      <template v-if="companyData.type == '已驳回'">
        <view class="page-title">驳回信息</view>
        <view class="page-card-div card-mag card-reject">
          <view class="card-row row-flex">
            <view class="card-row-left">驳回时间</view>
            <view class="card-row-right">{{
              utils.dateFormatter(
                companyData.rejectTime,
                "y-m-d h:i:s",
                2,
                true
              )
            }}</view>
          </view>
          <view class="card-row row-flex">
            <view class="card-row-left">驳回理由</view>
            <view class="card-row-right">{{ companyData.rejectText }} </view>
          </view>
        </view>
      </template>
      <!-- 按钮 -->
      <view class="btn-div-bottom" v-if="companyData.type == '邀约中'">
        <fui-button class="btn btn-primary" @click="handleCopy">复制</fui-button>
        <fui-button class="btn btn-primary-plain" @click="handleEdit">修改</fui-button>
      </view>
      <view class="btn-div" v-if="companyData.type == '已启用'">
        <fui-button class="btn btn-danger" @click="handleUnEnable"
          >停用</fui-button
        >
        <fui-button class="btn btn-primary" @click="openPopup">订单</fui-button>
      </view>
      <view class="btn-div" v-if="companyData.type == '已停用'">
        <fui-button class="btn btn-danger-plain" @click="handleDelete"
          >删除</fui-button
        >
        <fui-button class="btn btn-primary" @click="handleEnable"
          >启用</fui-button
        >
      </view>
      <view class="btn-div" v-if="companyData.type == '待审核'">
        <fui-button class="btn btn-danger-plain" @click="handleReject"
          >驳回</fui-button
        >
        <fui-button class="btn btn-primary" @click="handleResolve"
          >通过</fui-button
        >
      </view>
    </view>
    <!-- 查看证件弹窗 -->
    <fui-backdrop :show="isShow" closable @click="close">
      <checkPopup :childProp="popContent"></checkPopup>
    </fui-backdrop>
    <!-- 订单弹窗 -->
    <fui-bottom-popup :show="isOrderShow" @close="closePopup">
      <OrderPopup
        ref="orderPopup"
        api="getPurchaserOrderList"
        :companyId="companyData.id"
        @closeOrderPop="closePopup"
      ></OrderPopup>
    </fui-bottom-popup>
  </view>
</template>

<script setup>
import { ref, computed, watch, inject } from "vue";
import { onLoad, onShow, onPullDownRefresh } from "@dcloudio/uni-app";
import pageHeader from "@/components/header";
import CheckPopup from "@/components/popup/check";
import OrderPopup from "@/components/popup/order";
import purchaserApi from "@/api/purchaser";
import utils from "@/components/firstui/fui-utils";
import { maskPhoneNumber, maskIdCardNumber } from "@/utils/tools";
import config from "@/config";

const modal = inject("$modal");
const tab = inject("$tab");

onLoad((option) => {
  companyData.value.type = option.name;
  companyData.value.id = option.id;
  tagColorFun(companyData.value.type);
});
onShow(() => {
  getPurchaserDetail(companyData.value.id);
  getPurchaserBank(companyData.value.id);
});

// 银行信息
const getPurchaserBank = (id) => {
  purchaserApi.getPurchaserBank(id).then((res) => {
    if (res.code == 0) {
      const result = res.data || {};
      companyData.value.bankNname = result.bankAccountName;
      companyData.value.openBank = result.bankBranchName;
      companyData.value.bankID = result.account;
      companyData.value.filingsID = result.recordNumber;
      companyData.value.checkTime = result.checkTime;
    }
  });
};

// 采购方详情
const getPurchaserDetail = (id) => {
  purchaserApi.getPurchaserDetail(id).then((res) => {
    if (res.code == 0) {
      uni.stopPullDownRefresh(); // 终止下拉刷新动作
      companyData.value.userType = res.data.userType;
      companyData.value.title = res.data.userType === '0' ? res.data.companyName : res.data.adminName;
      companyData.value.code = res.data.creditCode;
      companyData.value.address = res.data.address;
      companyData.value.description = res.data.description;
      companyData.value.businessLicense = res.data.businessLicense;
      companyData.value.idcBack = res.data.idcBack;
      companyData.value.idcFront = res.data.idcFront;
      companyData.value.corporateName = res.data.corporationName;
      companyData.value.corporatePhone = res.data.corporationPhone;
      companyData.value.corporateID = res.data.corporationIdCard;
      companyData.value.headName = res.data.adminName; /*  */
      companyData.value.headPhone = res.data.adminPhone;
      companyData.value.headID = res.data.adminIdCard;
      companyData.value.rejectText = res.data.reviewedComments;
      companyData.value.rejectTime = res.data.reviewedTime;
      companyData.value.adminCardFront = res.data.adminCardFront;
      companyData.value.adminCardBack = res.data.adminCardBack;
    }
  });
};

const isPersonal = computed(() => companyData.value.userType === '1')

const tagsColor = ref({
  tagBack: "",
  tagColor: "",
});
// 公司信息
const companyData = ref({
  id: 1,
  title: "",
  code: "",
  businessLicense: "",
  isCompanyAuth: true, //是否公司认证
  isBankAuth: true, //是否银行认证
  type: "",
  loginPhone: "",
  address: "",
  description: "",
  // 法人信息
  corporateName: "",
  corporatePhone: "",
  corporateID: "",
  idcFront: "", //身份证正面
  idcBack: "", //身份证反面
  // 负责人信息
  headName: "",
  headPhone: "",
  headID: "",
  // 银行信息
  bankNname: "",
  openBank: "",
  bankID: "",
  filingsID: "",
  time: "",
  // 驳回信息
  rejectTime: "",
  rejectText: "",
});
let isEyesOpen = ref(true);
// 查看证件 传值
const popContent = ref({
  type: "",
  title: "",
  imgUrl: "",
  imgUrl1: "",
});
const isShow = ref(false);
// 订单弹窗
const isOrderShow = ref(false);
const moreState = ref(1);
const tagColorFun = (type) => {
  switch (type) {
    case "已停用":
      tagsColor.value.tagBack = "#e9e9e9";
      tagsColor.value.tagColor = "#666666";
      break;
    case "邀约中":
      tagsColor.value.tagBack = "#e8e5ff";
      tagsColor.value.tagColor = "#5A4BFA";
      break;
    case "已驳回":
      tagsColor.value.tagBack = "#fee8e8";
      tagsColor.value.tagColor = "#F95A5A";
      break;
    default:
      tagsColor.value.tagBack = "#e2eaff";
      tagsColor.value.tagColor = "var(--fui-color-primary)";
  }
};
// 判断tag标签
watch(
  companyData.value,
  () => {
    tagColorFun(companyData.value.type);
  },
  {
    immediate: true,
  }
);

// 点击眼睛显示字段
const eyesClick = (e) => {
  if (e == 1) {
    isEyesOpen.value = false;
  } else {
    isEyesOpen.value = true;
  }
};

// 点击遮罩层关闭
const close = () => {
  isShow.value = false;
  popContent.value = {};
};
// 点击底部弹出层打开
const orderPopup = ref(null);
const openPopup = () => {
  isOrderShow.value = true;
  orderPopup.value.openPopup();
};
// 点击底部弹出层关闭
const closePopup = () => {
  isOrderShow.value = false;
};
// 查看证件
const checkID = (type, url, urls) => {
  if (type == "img") {
    popContent.value = {
      type: "img",
      title: "查看营业执照",
      imgUrl: url,
    };
  } else {
    popContent.value = {
      type: "ID",
      title: "查看负责人证件",
      imgUrl: urls,
      imgUrl1: url,
    };
  }
  isShow.value = true;
};

// 更新采购方审核状态
const handleResolve = () => {
  modal.confirm(`您确认通过采购方“${companyData.value.title}”的申请？`).then(() => {
    purchaserApi
    .updatePurchaserStatus({
      id: companyData.value.id,
      attestationState: 2,
    })
    .then((res) => {
      if (res.code == 0) {
        modal.msg("审核完成");
        companyData.value.type = '已启用';
        tagColorFun(companyData.value.type);
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      }
    });
  });
};

const handleReject = () => {
  tab.navigateTo(
    `/pages/purchaser/view/reject?id=${
      companyData.value.id
    }&companyName=${encodeURIComponent(companyData.value.title)}`
  );
};

const handleEnable = () => {
  modal.confirm(`您确认启用“${companyData.value.title}”？`).then(() => {
    updatePurchaserUseStatus("1");
  });
};

const handleUnEnable = () => {
  modal.confirm(`您确认停用“${companyData.value.title}”？`).then(() => {
    updatePurchaserUseStatus("0");
  });
};

const handleCopy = () => {
  const text = `您好，${companyData.value.title}，邀请您加入${config.appInfo.platformName}，请您访问“云铂产业链”微信小程序，使用当前手机号登录，并完成认证，期待您的加入！`
  copyFun(text);
};

const handleEdit = () => {
  tab.navigateTo(
    `/pages/purchaser/view/add?companyId=${
      companyData.value.id
    }`
  );
};

const handleDelete = () => {
  modal.confirm(`您确认删除“${companyData.value.title}”？`).then(() => {
    purchaserApi.deletePurchaser(companyData.value.id).then((res) => {
      if (res.code == 0) {
        uni.showToast({
          title: "  删除成功  ",
          icon: "success",
          duration: 1500,
        });
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 1500);
      }
    });
  });
};

// 复制事件
const copyFun = (text) => {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        // 注意：在 Vue3 + script setup 中仍需使用 uni 对象来调用 showToast
        title: "  复制成功  ",
        icon: "success",
        duration: 1500,
      });
    },
    fail: (err) => {
      console.error("复制失败", err);
    },
  });
};

// 更新采购方使用状态
const updatePurchaserUseStatus = (status) => {
  purchaserApi
    .updatePurchaserUseStatus({
      id: companyData.value.id,
      useState: status,
    })
    .then((res) => {
      if (res.code == 0) {
        if (status == 0) {
          companyData.value.type = "已停用";
        } else {
          companyData.value.type = "已启用";
        }
        tagColorFun(companyData.value.type);
        getPurchaserDetail(companyData.value.id);
        modal.msg(`${status == 0 ? "已停用" : "已启用"}`);
      }
    });
};

// 下拉刷新加载更多
onPullDownRefresh(() => {
  getPurchaserDetail(companyData.value.id);
  getbank(companyData.value.id);
});
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
  overflow: scroll;

  .row-flex {
    display: flex;
    align-items: center;
  }

  .page-content {
    .page-card-div {
      width: 100%;
      background: #ffffff;
      padding: 24rpx;
      box-sizing: border-box;
      border-radius: 16rpx;

      .card-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333333;

        .img-icon {
          width: 50rpx;
          height: 45rpx;
          color: var(--fui-color-primary);
          margin-right: 12rpx;
        }
      }

      .card-tags {
        margin: 16rpx 0 0;

        :deep(.fui-tag__wrap) {
          display: block;
          height: 32rpx !important;
          line-height: 32rpx !important;
          font-size: 20rpx !important;
          padding: 4rpx 16rpx !important;
          margin-right: 20rpx !important;
        }
      }

      .card-row {
        align-items: flex-start;
        margin-top: 24rpx;
        font-size: 24rpx;
        color: #999999;

        &-left {
          width: 170rpx;
        }

        &-right {
          width: calc(100% - 170rpx);
          color: #333333;
          font-weight: bold;

          .icon-close-eyes {
            color: var(--fui-color-primary);
          }
        }

        .text-blue {
          color: var(--fui-color-primary);
        }
      }
    }

    .page-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333333;
      margin: 30rpx 0 20rpx;
    }

    .card-mag {
      padding-top: 2rpx;
    }

    .card-reject {
      margin-bottom: 30rpx;
    }

    .btn-div {
      margin-top: 100rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 40rpx;
    }

    .btn-div-bottom {
      position: fixed;
      bottom: 70rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: calc(100% - 72rpx);
    }

    .btn {
      flex: 1;
      height: 76rpx !important;
      margin: 0 20rpx !important;

      :deep(.fui-button__primary) {
        height: 76rpx !important;
      }
    }

    .btn-danger {
      :deep(.fui-button__primary) {
        border: 1px solid #f95a5a !important;
        background-color: #f95a5a !important;
        color: #ffffff !important;
      }
    }

    .btn-danger-plain {
      :deep(.fui-button__primary) {
        border: 1px solid #f95a5a !important;
        background-color: #ffffff !important;
        color: #f95a5a !important;
      }
    }

    .btn-primary {
      :deep(.fui-button__primary) {
        border: 1px solid var(--fui-color-primary) !important;
        background-color: var(--fui-color-primary) !important;
        color: #ffffff !important;
      }
    }

    .btn-primary-plain {
      :deep(.fui-button__primary) {
        border: 1px solid var(--fui-color-primary) !important;
        background-color: #ffffff !important;
        color: var(--fui-color-primary) !important;
      }
    }
  }

  :deep(.fui-bottom__popup) {
    height: 60%;
  }
}

::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条本身 */
  width: 0 !important;
  height: 0 !important;
  -webkit-appearance: none;
  background: transparent;
}
</style>